package com.tarry.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {
    public static void main(String[] args) {
        try (FileInputStream fileInputStream = new FileInputStream("./nio_test.txt");
             FileOutputStream fileOutputStream = new FileOutputStream("./宋词.txt");
             FileOutputStream targetOutputStream = new FileOutputStream("./宋词_2.txt")){
            // 读取文件通道
            final FileChannel inputStreamChannel = fileInputStream.getChannel();
            // 写文件通道
            final FileChannel outputStreamChannel = fileOutputStream.getChannel();
//            final ByteBuffer byteBuffer = ByteBuffer.allocate(1);
//            while (true) {
//                // 清空buffer
//                byteBuffer.clear();
//                final int read = inputStreamChannel.read(byteBuffer);
//                if (read == -1){
//                    break;
//                }
//                byteBuffer.flip();
//                outputStreamChannel.write(byteBuffer);
//            }

            // 通过 transferFrom 方法实现文件到快速拷贝 当文件大小，超过2G时，存在异常，需要分割续传
            targetOutputStream.getChannel().transferFrom(inputStreamChannel,0, inputStreamChannel.size());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
